package hku.cs.eclunuo.run;

import hku.cs.eclunuo.LunuoLog;
import hku.cs.eclunuo.LunuoPlugin;
import hku.cs.eclunuo.util.LunuoLibHelper;

import java.util.Arrays;
import java.util.List;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchManager;
import org.eclipse.debug.core.Launch;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.launching.IVMInstall;
import org.eclipse.jdt.launching.IVMRunner;
import org.eclipse.jdt.launching.JavaRuntime;
import org.eclipse.jdt.launching.VMRunnerConfiguration;

public class Runner {
	static final String MAIN_CLASS="hku.cs.lunuo.vmrun.SocketRunner";
	private IProject project;
	public Runner(IProject project) {
		this.project = project;
	}
	
	public void run(List<String> targetLst, List<String> testLst,
			List<String> copyLst, List<String> removeLst) throws CoreException {
		
		IJavaProject javaProject = JavaCore.create(project);
		IVMInstall vmInstall= getVMInstall();
		if (vmInstall == null)
			return;
			
		IVMRunner vmRunner= vmInstall.getVMRunner(ILaunchManager.RUN_MODE);
		if (vmRunner == null)
			return;
			
		String[] classPath= LunuoLibHelper.urlsToStringArray(LunuoLibHelper.getSootClassPath(javaProject));
		
		VMRunnerConfiguration vmConfig= new VMRunnerConfiguration(MAIN_CLASS, classPath);
		
		
		
		String[] args = new String[0];
		vmConfig.setProgramArguments(args);
		ILaunch launch= new Launch(null, ILaunchManager.RUN_MODE, null);
		
		vmRunner.run(vmConfig, launch, new NullProgressMonitor());
//		DebugPlugin.getDefault().getLaunchManager().addLaunch(launch);
		


	}
	
	private IVMInstall getVMInstall() throws CoreException {
		IJavaProject javaProject = JavaCore.create(project);
		IVMInstall vmInstall= JavaRuntime.getVMInstall(javaProject);
		if (vmInstall == null)
			vmInstall= JavaRuntime.getDefaultVMInstall();
		return vmInstall;
	}
}